<template>
  <div class="app-container">
    <!--顶部搜索条件-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="检测商品" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入检测商品"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检测时间">
        <el-date-picker
          v-model="checkTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="notDisposeList">
      <el-table-column label="商品名称" prop="goodsName" align="center" width="120" />
      <el-table-column label="检测项目" prop="itemName" align="center" width="220" />
      <el-table-column label="检测时间" prop="checkTime" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上报状态" prop="reportStatus" align="center" width="150">
        <template slot-scope="scope">
          <span>
            {{ selectDictLabels(dict.type.check_report_status,scope.row.reportStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="数据来源" prop="dataSource" align="center" width="120">
        <template slot-scope="scope">
          <span>
            {{ selectDictLabels(dict.type.check_data_source,scope.row.dataSource) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="检测值" prop="checkValue" align="center" width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding" fixed="right" min-width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleDispose(scope.row)"
            v-hasPermi="['check:dispose:operate']"
          >处置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加对话框 -->
    <el-dialog title = "处置" :visible.sync="open" width="800px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="处置时间" prop="disposeTime">
              <el-date-picker
                v-model="form.disposeTime"
                type="datetime"
                style="width: 100%;"
                placeholder="选择日期时间"
                default-time="12:00:00">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处置数量" prop="disposeNum">
              <el-input-number v-model="form.disposeNum" style="width: 100%" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="处置人" prop="disposePeople">
              <el-input v-model="form.disposePeople" placeholder="请输入处置人" maxlength="32" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处置结果" prop="disposeResult">
              <el-input v-model="form.disposeResult" placeholder="请输入处置结果" maxlength="32"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="处置方式" prop="disposeType">
              <el-input v-model="form.disposeType" placeholder="请输入处置方式" maxlength="32" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--处置人签名-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="处置人签名" prop="signUrl">
              <el-upload
                ref="uploadSignUrl"
                :action="uploadUrl"
                :headers="headers"
                v-model="form.sign"
                :limit="1"
                list-type="picture-card"
                :on-preview="handleSignUrlPreview"
                :on-success="handleSignUrlUploadSuccess"
                :on-exceed="checkHasSignUrl"
                :on-remove="handleSignUrlRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="signUrlOpen" width="400px" append-to-body>
                <img width="100%" :src="form.signUrl" alt="">
              </el-dialog>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <span style="color: red">注意：附件图片和视频需要至少上传其中一项</span>
          </el-col>
        </el-row>
        <!--附件，图片类型-->
        <el-row style="margin-top: 20px">
          <el-col :span="24">
            <el-form-item label="附件(图片)" prop="imageAttachList">
              <el-upload
                ref="imageAttachList"
                :action="uploadUrl"
                v-model="imageAttachUrl"
                :headers="headers"
                list-type="picture-card"
                :on-preview="handleImageAttachPreview"
                :on-success="handleImageAttachUploadSuccess"
                :on-remove="handleImageAttachRemove"
                :before-upload="checkImageAttachType"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="imageAttachOpen" width="400px" append-to-body>
                <img width="100%" :src="imageAttachUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <!--附件，视频类型-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件(视频)" prop="videoAttachList">
              <el-upload
                ref="videoAttachList"
                :action="uploadUrl"
                :headers="headers"
                v-model="videoAttachList"
                :on-success="handleVideoAttachUploadSuccess"
                :on-remove="handleVideoAttachRemove"
                :before-upload="checkVideoAttachType"
                :file-list="videoAttachList"
                list-type="picture-card">
                <i class="el-icon-plus"></i>
                <!-- 自定义每个文件展示内容 -->
                <template slot="file" slot-scope="{file}">
                  <div class="custom-file">
                    <!-- 如果是视频 -->
                    <video
                      :src="file.url || (file.response && file.response.url)"
                      controls
                      style="width: 100%; height: 100%; object-fit: cover;"
                    ></video>
                    <!-- 操作按钮区 -->
                    <span class="el-upload-list__item-actions">
              <!-- 放大预览 -->
              <span
                class="el-upload-list__item-preview"
                @click="handleVideoAttachPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
                      <!-- 删除 -->
              <span
                class="el-upload-list__item-delete"
                @click="handleVideoAttachRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
                  </div>
                </template>
                <!-- 弹窗预览视频/图片 -->
                <el-dialog :visible.sync="videoAttachOpen" width="800px" append-to-body>
                  <video :src="videoAttachUrl" controls style="width: 100%;"></video>
                </el-dialog>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
//待处置组件
import {addDispose, listNotDispose} from "@/api/check/dispose";
import {addDetection, getDetection} from "@/api/check/detection";
import {getToken} from "@/utils/auth";

export default {
  name: "unprocessed",
  dicts: ['check_report_status','check_data_source'],
  data(){
    return {
      queryParams: {
        goodsName: undefined,
        pageNum: 1,
        pageSize: 10,
      },
      checkTime: [],
      showSearch: true,
      loading: false,
      notDisposeList: [],
      total: 0,
      open: false,
      form: {},
      rules: {
        disposeTime: [
          { required: true, message: "处置时间不能为空", trigger: "blur" }
        ],
        disposeNum: [
          { required: true, message: "处置数量不能为空", trigger: "blur" }
        ],
        disposePeople: [
          { required: true, message: "处置人不能为空", trigger: "blur" }
        ],
        disposeResult: [
          { required: true, message: "处置结果不能为空", trigger: "blur" }
        ],
        disposeType: [
          { required: true, message: "处置方式不能为空", trigger: "blur" }
        ],
        signUrl: [
          { required: true, message: "处置人签名不能为空", trigger: "blur" }
        ]
      },
      signUrlOpen: false,
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: { Authorization: "Bearer " + getToken() },
      imageAttachUrl: "",
      imageAttachOpen: false,
      videoAttachList: [],
      videoAttachUrl: "",
      videoAttachOpen: false
    }
  },
  created() {
    this.initCheckTime()
  },
  methods: {
    initCheckTime(){
      // 使用
      const today = new Date();
      const endTime = this.formatDate(today);

      const start = new Date();
      start.setDate(today.getDate() - 6);
      const startTime = this.formatDate(start);
      this.checkTime = [startTime,endTime]
    },
    formatDate(date) {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const d = String(date.getDate()).padStart(2, '0');
      return `${y}-${m}-${d}`;
    },
    getList(){
      this.loading = true
      listNotDispose(this.addDateTimeRange(this.queryParams,this.checkTime)).then(response => {
        this.notDisposeList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleQuery(){
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery(){

    },
    reset(){
      this.form = {
        detectionId: undefined,
        goodsName: undefined,
        itemId: undefined,
        itemName: undefined,
        checkTime: undefined,
        disposeTime: undefined,
        disposeNum: undefined,
        disposePeople: undefined,
        disposeResult: undefined,
        disposeType: undefined,
        signUrl: undefined,
        remark: undefined,
        imageAttachList: [],
        videoAttachList: []
      }
      if (this.$refs.uploadSignUrl){
        this.$refs.uploadSignUrl.clearFiles()
      }
      if (this.$refs.imageAttachList){
        this.$refs.imageAttachList.clearFiles()
      }
      if (this.$refs.videoAttachList){
        this.$refs.videoAttachList.clearFiles()
      }
    },
    handleDispose(row){
      this.reset()
      getDetection(row.id).then(response => {
        this.form = response.data
        this.form.disposeTime = new Date();
        this.form.signUrl = ""
        this.form.imageAttachList = []
        this.form.videoAttachList = []
        this.open = true
      })
    },
    handleSignUrlPreview(file){
      this.form.signUrl = file.url;
      this.signUrlOpen = true;
    },
    handleSignUrlRemove(file, fileList){
      this.$set(this.form,'signUrl','')
    },
    // 文件上传成功处理
    handleSignUrlUploadSuccess(response, file, fileList) {
      this.$modal.msgSuccess("上传成功")
      this.$set(this.form,'signUrl',response.url)
    },
    checkHasSignUrl(){
      if (this.form.signUrl){
        this.$modal.msgError("处置人签名只需上传一张即可")
      }
    },
    handleImageAttachPreview(file){
      this.imageAttachUrl = file.url;
      this.imageAttachOpen = true;
    },
    handleImageAttachUploadSuccess(response, file, fileList){
      this.$modal.msgSuccess("上传成功")
      this.form.imageAttachList.push(response.url)
    },
    handleImageAttachRemove(file, fileList){
      // 只处理有 response 的情况
      if (file.response && file.response.url) {
        this.form.imageAttachList = this.form.imageAttachList.filter(
          item => item !== file.response.url
        )
      }
    },
    checkImageAttachType(file){
      const isImage = (file.type === 'image/jpeg' || file.type === 'image/png');
      //限定2m以内
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error('上传文件类型错误，必须为png，jpg，jpeg格式');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    handleVideoAttachPreview(file){
      this.videoAttachUrl = file.url;
      this.videoAttachOpen = true;
    },
    handleVideoAttachUploadSuccess(response, file, fileList){
      this.$modal.msgSuccess("上传成功")
      this.form.videoAttachList.push(response.url)
      this.videoAttachList = fileList // 同步更新绑定的 file-list
    },
    handleVideoAttachRemove(file, fileList){
      // 只处理有 response 的情况
      if (file.response && file.response.url) {
        this.form.videoAttachList = this.form.videoAttachList.filter(
          item => item !== file.response.url
        )
      }
      this.videoAttachList = fileList // 关键！必须赋值，否则页面不会更新
    },
    checkVideoAttachType(file){
      const isVideo = file.type === 'video/mp4'
      //限定2m以内
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isVideo) {
        this.$message.error('上传文件类型错误，必须为mp4格式');
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB');
      }
      return isVideo && isLt2M;
    },
    submitForm(){
      if (!this.form.videoAttachList || !this.form.imageAttachList){
        this.$modal.msgError("附件图片和视频需要至少上传其中一项")
      }else {
        this.$refs["form"].validate(valid => {
          if (valid){
            addDispose(this.form).then(response => {
              this.$modal.msgSuccess("处置成功")
              this.open = false
              this.getList()
            })
          }
        })
      }
    },
    cancel(){
      this.open = false
      this.reset()
    }
  }
}
</script>

<style>
.custom-file {
  position: relative;
  width: 100%;
  height: 100%;
}
.custom-file video,
.custom-file img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
